package com.oa.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oa.mapper.user.TaskDescMapper;
import com.oa.mapper.user.TaskMapper;
import com.oa.mapper.user.UserMapper;
import com.oa.pojo.Emp;
import com.oa.pojo.Task;
import com.oa.pojo.TaskDesc;
import com.oa.service.user.TaskService;
import com.oa.vo.PageResult;
import com.oa.vo.TaskFileUploadVO;
import com.oa.vo.TaskVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class TaskImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TaskDescMapper taskDescMapper;

    @Value("${oa.resource.path:E:/images}")
    private String resourcePath;

    @Value("${oa.resource.host:http://localhost:8093/}")
    private String resourceHost;

    /**
     * 新增任务
     *
     * @param task
     */
    @Override
    public void addTask(Task task) {
        taskMapper.insert(task);
        List<String> fileList = task.getFileList();
        Integer taskId = taskMapper.selectOne(new QueryWrapper<>(task)).getId();
        List<TaskDesc> list = new ArrayList<>(fileList.size());
        for (String s : fileList) {
            list.add(new TaskDesc().setTaskId(taskId).setTaskFile(s));
        }
        taskDescMapper.insertTaskFile(list);
    }

    @Override
    public void updateTask(Task task) {
        Date date = new Date();
        System.out.println(task);
        task.setUpdateTime(date);
        if (task.getTaskStatus() == 1) {
            task.setEndTime(date);
        } else {
            task.setEndTime(null);
        }
        taskMapper.updateById(task);
    }

    @Override
    public void deleteTask(Task task) {
        taskMapper.deleteById(task);
        QueryWrapper<TaskDesc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", task.getId());
        taskDescMapper.delete(queryWrapper);
    }

    /**
     * 任务列表分页查询
     *
     * @param page       分页信息
     * @param pageResult 其他查询条件
     * @return 查询结果
     */
    @Override
    public Page<TaskVO> getTaskList(Page<TaskVO> page, PageResult pageResult) {
        return taskMapper.selectTaskInfo(page, pageResult.getQuery(), pageResult.getEmpId());
    }

    @Override
    public List<Task> findAll() {
        return taskMapper.selectList(null);
    }

    @Override
    public Task getTaskInfo(Task task) {
        return taskMapper.selectById(task);
    }

    @Override
    public List<Emp> getEmpListByDep(Integer depId) {
        return userMapper.selectList(new QueryWrapper<Emp>().eq("dep_id", depId));
    }

    @Override
    public Page<TaskVO> getPerformList(Page<TaskVO> page, PageResult pageResult) {
        return taskMapper.selectPerformTask(page, pageResult.getQuery(), pageResult.getEmpId());
    }

    @Override
    public TaskFileUploadVO uploadTaskFile(MultipartFile file) throws IOException {
        String dateStr = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        File uploadDir = new File(resourcePath, dateStr);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        //原文件名
        String sourceFileName = file.getOriginalFilename();
        String filePrefix = UUID.randomUUID().toString();
        assert sourceFileName != null;
        String fileSuffix = sourceFileName.substring(sourceFileName.lastIndexOf("."));
        String newFileName = filePrefix + fileSuffix;
        file.transferTo(new File(uploadDir, newFileName));
        String accessAddress = resourceHost + dateStr + "/" + newFileName;
        log.info("文件上传地址为:{}", accessAddress);
        return new TaskFileUploadVO().setFileName(sourceFileName).setUrlPath(accessAddress).setDateStr(dateStr);
    }

    @Override
    public List<TaskDesc> getTaskFile(Integer taskId) {
        return taskDescMapper.selectList(new QueryWrapper<TaskDesc>().eq("task_id", taskId));
    }

    @Override
    public Task getCurrentTask(Integer id) {
        return taskMapper.selectById(id);
    }

    @Override
    public Integer deleteTaskFile(String key) {
        String filePath = resourcePath + "/" + key;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        return 200;
    }

}
